import wtforms
from wtforms.validators import Email, Length, EqualTo
from easyRead.models import User
from flask import session

class RegisterForm(wtforms.Form):
    id = wtforms.StringField(validators=[Length(min=10, max=10, message="学工号格式错误！")])
    email = wtforms.StringField(validators=[Email(message="邮箱格式错误！")])
    captcha = wtforms.StringField(validators=[Length(min=4, max=4, message="验证码格式错误！")])
    nickname = wtforms.StringField(validators=[Length(min=3, max=10, message="用户名格式错误！")])
    password = wtforms.StringField(validators=[Length(min=6, max=20, message="密码格式错误！")])
    password_confirm = wtforms.StringField(validators=[EqualTo("password", message="两次密码不一致！")])
    phone = wtforms.StringField(validators=[Length(min=11, max=11, message="电话号码格式错误！")])
    level = wtforms.SelectField(label='level', choices=(('student', '学生'), ('teacher', '老师')))

    # 1. 邮箱是否已经被注册
    def validate_id(self, field):
        id = field.data
        user = User.query.filter_by(id=id).first()
        if user:
            raise wtforms.ValidationError(message="该学工号已经被注册！")

    # 2. 邮箱是否已经被注册
    def validate_email(self, field):
        email = field.data
        user = User.query.filter_by(email=email).first()
        if user:
            raise wtforms.ValidationError(message="该邮箱已经被注册！")

    # 3. 验证码是否正确
    def validate_captcha(self, field):
        captcha = field.data  # 用户输入的验证码
        captcha_true = session.get('captcha')  # 系统生成的验证码
        print(captcha_true)
        if captcha_true != captcha:
            raise wtforms.ValidationError(message="邮箱或验证码错误！")
        else:
            session.pop('captcha')



class LoginForm(wtforms.Form):
    id = wtforms.StringField(validators=[Length(min=10, max=10, message="学工号格式错误！")])
    password = wtforms.StringField(validators=[Length(min=6, max=20, message="密码格式错误！")])

class EmailForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message="邮箱格式错误！")])

class PasswordForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message="邮箱格式错误！")])
    captcha = wtforms.StringField(validators=[Length(min=4, max=4, message="验证码格式错误！")])
    password = wtforms.StringField(validators=[Length(min=6, max=20, message="密码格式错误！")])
    password_confirm = wtforms.StringField(validators=[EqualTo("password", message="两次密码不一致！")])
    # 重置密码时必须有相应邮箱
    def validate_email(self, field):
        email = field.data
        user = User.query.filter_by(email=email).first()
        if not user:
            raise wtforms.ValidationError(message="找不到该邮箱！")
    def validate_captcha(self, field):
        captcha = field.data  # 用户输入的验证码
        captcha_true = session.get('captcha')  # 系统生成的验证码
        if captcha_true != captcha:
            raise wtforms.ValidationError(message="验证码错误！")
        else:
            session.pop('captcha')
